package group.sicher.core.web.context;

import group.sicher.core.exception.ResponseException;
import org.springframework.util.StringUtils;

/**
 * @description: 会话上下文
 * @author: aron
 * @date: 2019-04-03 09:55
 */
public class SicherContext {

    private static ThreadLocal<HxContextEntry> CONTEXT = new ThreadLocal<>();

    public static void setContext(HxContextEntry context) {
        CONTEXT.set(context);
    }

    public static void removeContext() {
        CONTEXT.remove();
    }

    public static Long getUserId() {
        HxContextEntry entry = CONTEXT.get();
        Long userId = null == entry ? null : entry.getUserId();
        if (null == userId) {
            throw new ResponseException("会话上下文没有设置");
        }
        return userId;
    }

    public static String getToken() {
        HxContextEntry entry = CONTEXT.get();
        String token = null == entry ? null : entry.getToken();
        if (StringUtils.isEmpty(token)) {
            throw new ResponseException("会话上下文没有设置");
        }
        return token;
    }

    public static Object getObject() {
        HxContextEntry entry = CONTEXT.get();
        Object object = null == entry ? null : entry.getObject();
        if (StringUtils.isEmpty(object)) {
            throw new ResponseException("会话上下文没有设置");
        }
        return object;
    }
}
